<template>
  <el-drawer :model-value="drawerVisible" direction="rtl" @close="closeDrawer">
    <template #header>
      <h4>{{ title[drawerType] }}</h4>
    </template>
    <template #default>
      <el-form
        v-show="drawerType === 0"
        :model="userInfo"
        :rules="rules"
        ref="form1Ref"
      >
        <el-form-item label="用户账号" prop="name">
          <el-input v-model="userInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="username"
          ><el-input v-model="userInfo.username"></el-input
        ></el-form-item>
        <el-form-item label="用户密码" prop="password"
          ><el-input v-model="userInfo.password"> </el-input
        ></el-form-item>
      </el-form>
      <el-form
        v-show="drawerType === 1"
        :model="userInfo"
        ref="form2Ref"
        :rules="rules2"
      >
        <el-form-item label="用户账号" prop="name">
          <el-input v-model="userInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="username"
          ><el-input v-model="userInfo.username"></el-input
        ></el-form-item>
      </el-form>
      <el-form v-show="drawerType === 2" :model="userInfo">
        <el-form-item label="用户账号"
          ><el-input v-model="userInfo.name" :disabled="true"> </el-input
        ></el-form-item>
        <el-form-item label="分配角色">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="checkedRoles"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="role in roles"
              :key="role.id"
              :label="role.id"
              :value="role.id"
              style="width: 120px"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import {
  reqAssignRolesForUser,
  reqGetAllRoles,
  reqGetUserInfoById,
  reqSaveUserInfo,
  reqUpdateUser,
} from "../../../api/acl/user";
import { ElMessage } from "element-plus";
const checkAll = ref(false);
const isIndeterminate = ref(true);
const checkedRoles = ref([]);
const roles = ref([]);
const allRoleId = ref([]);
const form1Ref = ref();
const form2Ref = ref();
const rolesInfo = reactive({});
const emit = defineEmits(["close"]);
const rules = {
  name: [{ required: true, min: 5, max: 11 }],
  username: [{ required: true }],
  password: [{ required: true }],
};
const rules2 = {
  name: [{ required: true, min: 5, max: 11 }],
  username: [{ required: true, min: 2 }],
};
const userInfo = reactive({ name: "", username: "", password: "" });
const props = defineProps({
  drawerVisible: {
    type: Boolean,
    default: false,
  },
  drawerType: {
    type: Number,
    default: 0,
  },
  userId: {
    type: Number,
  },
});
watch(
  () => props.drawerVisible,
  async () => {
    nextTick(() => {
      form1Ref.value.resetFields();
      form2Ref.value.resetFields();
    });
    Object.assign(userInfo, { name: "", username: "", password: "", id: 0 });
    // 编辑时需要获取数据
    if (props.drawerType === 1 || props.drawerType === 2) {
      let result = await reqGetUserInfoById(props.userId as number);
      Object.assign(userInfo, result.data);
      console.log(userInfo);
    }
    if (props.drawerType === 2) {
      let result = await reqGetAllRoles(props.userId);
      roles.value = result.data.allRolesList;
      // 所有角色
      roles.value.forEach((item: any) => {
        allRoleId.value.push(item.id);
      });
      // 已分配的角色
      result.data.assignRoles.forEach((item: any) => {
        checkedRoles.value.push(item.id);
      });
    }
  }
);
const title = ["添加用户", "编辑用户"];
const cancelClick = () => {
  console.log(userInfo);
  emit("close");
};
const confirmClick = async () => {
  if (props.drawerType === 0) {
    form1Ref.value.validate(async (valid: any) => {
      //   console.log(props.drawerType === 0);

      if (!valid) return;
      let result = await reqSaveUserInfo(userInfo);
      if (result.code === 200) {
        ElMessage.success("添加成功");
        emit("close");
      } else {
        ElMessage.error("添加失败");
      }
    });
  } else if (props.drawerType === 1) {
    form2Ref.value.validate(async (valid: any) => {
      //   console.log(props.drawerType === 0);

      if (!valid) return;
      let result = await reqUpdateUser(userInfo);
      if (result.code === 200) {
        ElMessage.success("修改成功");
        emit("close");
        window.location.reload();
      } else {
        ElMessage.error("修改失败");
        emit("close");
      }
    });
  } else {
    Object.assign(rolesInfo, {
      userId: props.userId,
      roleIdList: checkedRoles.value,
    });
    let result = await reqAssignRolesForUser(rolesInfo);
    console.log(result);
    emit("close");
  }
};
const closeDrawer = () => {
  emit("close");
};
onMounted(() => {
  Object.assign(userInfo, { name: "", username: "", password: "" });
});

const handleCheckAllChange = (val: boolean) => {
  checkedRoles.value = val ? allRoleId.value : [];
  isIndeterminate.value = false;
};
const handleCheckedRolesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === roles.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length;
  console.log(checkedRoles.value);
  console.log(value);
};
</script>

<style lang="scss" scoped></style>
